#!/usr/bin/python
import os
import re
from mechanize import Browser
from os import listdir
from os.path import isfile, join

current_path = os.path.dirname(os.path.realpath(__file__))
script_path = join(current_path, "src/main/bin")
onlyfiles = [f for f in listdir(script_path) if isfile(join(script_path, f))]

output_dir = '/tmp/dn_scripts_obs'
if not os.path.exists(output_dir): os.makedirs(output_dir)
output_files = [f for f in listdir(output_dir) if isfile(join(output_dir, f))]

br = Browser()
br.open("http://liraz.org/obfus.html")
for perl_script in onlyfiles:
  if (not re.search(".*\.p[lm]$", perl_script)):
    continue
  if (perl_script in output_files):
    continue

  print
  "Obfuscating script %s ..." % perl_script
  perl_in = open(join(script_path, perl_script))

  br.select_form(nr=0)
  br['perlText'] = perl_in.read()

  response = br.submit(name="submitText")  # submit current form
  perl_in.close()

  perl_out = open(join(output_dir, perl_script), "w")
  perl_out.write(response.read())
  perl_out.close()

  br.back()

  '''
  print "-----before obfuscate"
  print br['perl']
  print "+++++after obfuscate"
  print br['result']
  '''

print
"*** Done obfuscation!***"
